import 'package:flutter/material.dart';
import 'package:flutter_app/app/models/movie.dart';
import 'package:flutter_app/config/keys.dart';
import 'package:flutter_app/resources/pages/play_page.dart';
import 'package:nylo_framework/nylo_framework.dart';
import 'package:flutter_app/resources/widgets/cover_widget.dart';

class HistoryPage extends NyStatefulWidget {
  static RouteView path = ("/history", (_) => HistoryPage());

  HistoryPage({super.key}) : super(child: () => _HistoryPageState());
}

class _HistoryPageState extends NyPage<HistoryPage> {
  List<MoviesList> history = [];

  @override
  get init => () async {
        await getHistory();
      };

  @override
  Widget view(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(child: Text("观看历史")),
      ),
      body: SafeArea(
        child: NyListView(
            padding: EdgeInsets.all(10),
            child: (BuildContext context, dynamic data) {
              data as MoviesList;
              return Padding(
                child: Cover(
                  movie: data,
                  onClick: (movie) {
                    routeTo(PlayPage.path, data: movie);
                  },
                ),
                padding: EdgeInsets.only(
                  bottom: 10,
                ),
              );
            },
            data: () async {
              return history;
            }),
      ),
    );
  }

  Future<void> getHistory() async {
    try {
      // Read raw data from storage
      dynamic rawHistory = await storageRead(Keys.history);
      print("history${rawHistory}");
      // Convert raw data to List<MoviesList>
      if (rawHistory != null) {
        if (rawHistory is List) {
          history = rawHistory.map<MoviesList>((item) {
            if (item is MoviesList) {
              return item;
            } else if (item is Map<String, dynamic>) {
              return MoviesList.fromJson(item); // Assuming you have fromJson
            }
            throw Exception('Invalid history item type');
          }).toList();
        }
      }
    } catch (e) {
      print("Error in setHistory: $e");
      rethrow;
    }
  }
}
